<?php
namespace app\business\controller\api;

use app\admin\service\UserService;
use think\admin\Controller;
use think\cache\driver\Redis;

/**
 * 商户用户登录
 * Class Login
 * @package app\data\controller\api
 */
class Login extends Controller
{
    /**
     * 接口认证类型
     * @var string
     */
    private $type;

    /**
     * 绑定数据表
     * @var string
     */
    protected $table = 'DataUser';

    /**
     * 控制器初始化
     */
    protected function initialize()
    {
        $this->type = input('api', UserService::APITYPE_WAP);
        if (empty(UserService::TYPES[$this->type])) {
            $this->error("接口通道[{$this->type}]未定义规则！");
        }
    }

    public function in(){
        $data = $this->_vali([
            'username.require' => '登录账号不能为空!',
            'username.min:4'   => '登录账号不能少于4位字符!',
            'password.require' => '登录密码不能为空!',
            'password.min:4'   => '登录密码不能少于4位字符!',
        ]);
        $map = ['username' => $data['username'], 'is_deleted' => '0'];
        $user = $this->app->db->name('SystemUser')->where($map)->order('id desc')->find();
        if (empty($user)) {
            $this->app->session->set("login_input_session_error", true);
            $this->error('登录账号或密码错误，请重新输入!');
        }
        if ($user['password'] !== $data['password']) {
            $this->app->session->set("login_input_session_error", true);
            $this->error('登录账号或密码错误，请重新输入!');
        }
        if (empty($user['status'])) {
            $this->error('账号已经被禁用，请联系管理员!');
        }

        $token = UserService::instance()->token(intval($user['id']), UserService::APITYPE_WAP);
        if(!$token[0]){
            $this->error('账号登录失败，请稍候再试！');
        }

        $user['stores'] = str2arr($user['stores'] ?? '');

        $authorize = str2arr($user['authorize']);
        if(array_intersect([1,3], $authorize) && in_array(3, $authorize)){
            $user['stores'] = $this->app->db->name("jcg_store")->where("sales_id", $user['id'])->column("id");
        }

        if(!is_array($user['stores'])){
            $this->error('账号未授权，或不是商户账号！');
        }

        $this->app->db->name('SystemUser')->where(['id' => $user['id']])->update([
            'login_ip'  => $this->app->request->ip(),
            'login_at'  => $this->app->db->raw('now()'),
            'login_num' => $this->app->db->raw('login_num+1'),
        ]);
        sysoplog('系统用户登录', '登录商户端成功');

        $result = [
            'user_id'=>$user['id'],
            'nickname' => $user['nickname'],
            'role_id' => (int)$authorize[0]??0,
            'token' => [
                'token'=> $token[2]['token'],
                'expire'=> $token[2]['time'],
            ]
        ];

        $redis = new Redis();
        $redis->set("sys_store_user_".$user['id'], ['id'=>$user['id'], 'stores'=>$user['stores'], 'nickname'=>$user['nickname'], 'role_id'=>$authorize[0]??0], 7200);

        $this->success('登录成功！', $result);
    }
}